package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.校验参数
        dto.checkParam();

        //2.分页条件查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //按照状态精确查询
        if(dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //按照时间范围查询
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            lambdaQueryWrapper.between(WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //按照频道精确查询
        if(dto.getChannelId() != null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //按照关键字模糊查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //按照时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //指定当前用户查询
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());

        page = this.page(page,lambdaQueryWrapper);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        //3.结果返回
        return responseResult;
    }

    /*@Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;*/

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 提交（修改）或保存草稿
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {

        //1.校验参数
        if(dto == null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存或修改文章
        WmNews wmNews = saveOrUpdateNews(dto);

        //3.判断是否为草稿，是草稿，就结束方法
        if(dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //提取文章内容中的图片列表
        List<String> materials =  ectractUrlInfo(dto.getContent());

        //4.保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materials,wmNews.getId());

        //5.保存文章封面图片与素材的关系
        // 如果类型选择的自动，则到文章内容中匹配图片作为封面图片，重新设置封面类型
        saveRelativeInfoForCover(dto,materials,wmNews);

       /* //异步调用文章审核
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());*/
        wmNewsTaskService.addWmNewsToTask(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     *  1.保存文章封面图片与素材的关系
     *  2.如果类型选择的自动，则到文章内容中匹配图片作为封面图片，重新设置封面类型
     *  匹配规则
     *  内容的图片的个数 >=1  && < 3  单图=type
     *  内容的图片的个数 >3  多图=type
     *  内容没有图片，无图=type
     * @param dto
     * @param materials
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {

        List<String> images = dto.getImages();

        //如果类型选择的自动，则到文章内容中匹配图片作为封面图片，重新设置封面类型
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            int size = materials.size();
            if(size >= 1 && size < 3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());

            }else if(size >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());

            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //修改文章
            if(images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
                this.updateById(wmNews);
            }
        }

        //保存文章封面图片与素材的关系
        saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);

    }

    /**
     * 保存文章内容图片与素材的关系
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 真正的保存文章图片与素材的关系
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {

        if(materials != null && materials.size() > 0){
            //去重
            materials = materials.stream().distinct().collect(Collectors.toList());

            //通过素材的访问路径找到素材的id
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            //需要判断，查询出来的数据跟素材的url的个数保持一致
            if(dbMaterials == null || dbMaterials.size() == 0 || dbMaterials.size() != materials.size()){
                //提示用户，素材失效了
                //回滚事务
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);

            }
            //素材的id列表
            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            /*List<Integer> minList = new ArrayList<>();
            for (WmMaterial dbMaterial : dbMaterials) {
                minList.add(dbMaterial.getId());
            }*/

            //保存关系
            wmNewsMaterialMapper.saveRelations(idList,newsId,type);

        }



    }


    /**
     * 提取文章内容中的图片列表
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {

        List<String> imageList = new ArrayList<>();

        //解析json格式
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                imageList.add((String) map.get("value"));
            }
        }


        return imageList;

    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     * @param dto
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {

        //创建文章对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //处理封面图片
        //[dsfdsfdf.jpg,lsdjflkdsjfl.jpg]-->dsfdsfdf.jpg,lsdjflkdsjfl.jpg
        if(dto.getImages() != null && dto.getImages().size() > 0){

            //dto.getImages().toString().replace("]","").replace("[","");
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagesStr);
        }
        //封面的类型
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //补充其他字段
        wmNews.setEnable((short)1);//默认上架
        wmNews.setSubmitedTime(new Date());
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());

        if(dto.getId() == null){
            //保存
            this.save(wmNews);
        }else {
            //删除文章与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,dto.getId()));
            //修改
            this.updateById(wmNews);
        }
        return wmNews;
    }
}
